<template>
	<view class="area-wrap">
		<view class="area-mask" @click="state.show = true">{{ state.text }}</view>
		<up-picker
			:show="state.show" 
			:columns="state.columns" 
			:defaultIndex="state.defaultIndex"
			keyName="name" 
			@confirm="confirm"
			@change="changeHandler" />
	</view>
</template>

<script setup>
	import { onMounted, reactive } from "vue";
	import { area } from "@/api/public.js"
	const emit = defineEmits(["confirm"])
	const state = reactive({
		show: false,
		columns: [],
		defaultIndex: [0, 0, 0],
		text: ""
	})
	// 初始化
	const initArea = () => {
		// 省
		area({ type: "province", code: 0 }).then(res => {
			state.columns[0] = res.content
			// 市
			area({ type: "city", code: res.content[0].code }).then(res => {
				state.columns[1] = res.content
				// 区县
				area({ type: "area", code: res.content[0].code }).then(res => {
					state.columns[2] = res.content
				})
			})
		})
	}
	
	const changeHandler = (e) => {
		const columnIndex = e.columnIndex
		// code
		const code = e.value[columnIndex]?.code
		// 省
		if(code && columnIndex === 0) {
			// 市
			area({ type: "city", code }).then(res => {
				state.columns[1] = res.content
				// 区县
				area({ type: "area", code: res.content[0].code }).then(res => {
					state.columns[2] = res.content
					state.defaultIndex = [e.index, 0, 0]
				})
			})
		}
		
		// 市
		if(code && columnIndex === 1) {
			// 区县
			area({ type: "area", code }).then(res => {
				state.columns[2] = res.content
				state.defaultIndex = [e.indexs[0], e.index, 0]
			})
		}
	}
	
	const confirm = (e) => {
		const ids = e.value.map(item => item.code)
		state.show = false
		state.text = e.value.map(item => item.name).join(' / ')
		emit("confirm", ids)
	}
	
	onMounted(() => {
		initArea()
	})
</script>

<style lang="scss" scoped>
.area-wrap {
	position: relative;
	height: 90rpx;
	.area-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 2;
		display: flex;
		align-items: center;
	}
}
</style>